package jmind.core.jdbc;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import jmind.base.util.GlobalConstants;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * 数据库配置
 * @author weibo.xie
 * 2011-7-25
 */
public class DatabaseConfig {

    private final Map<String, String> map;

    private String[] database;

    public DatabaseConfig(String name) {
        map = new ConcurrentHashMap<String, String>();
        try {
            Document doc = Jsoup.parse(getClass().getClassLoader().getResourceAsStream(name), "UTF-8", "");
            database = doc.getElementsByTag("database").first().attr("name").split(GlobalConstants.POUND_SIGN);
            Elements tables = doc.select("sqls");
            for (Element table : tables) {
                String tableName = table.attr("name");
                Elements sqls = table.select("sql");
                for (Element sql : sqls) {
                    map.put(tableName + GlobalConstants.POUND_SIGN + sql.attr("name"), sql.text().trim());
                    //System.out.println("load=" + tableName + separator + sql.attr("name"));
                }

            }
        } catch (IOException e) {
            System.err.println("err file=" + name);
            e.printStackTrace();
        }
    }

    public String getDatabase(int index) {
        return database[index];
    }

    public String getSql(String key) {
        return map.get(key);
    }

    public String getSql(String prefix, String suffix) {
        return map.get(prefix + GlobalConstants.POUND_SIGN + suffix);
    }

}
